<?php

namespace app\lib;

use app\lib\enum\enum_redis_key;
use thirds\sms\sms;

class base_sms extends base
{
    public function send_sms(string $mobile, int $type, int $limit = 3)
    {
        //验证码
        $time     = time();
        $sms_code = mt_rand(100000, 999999);

        //缓存
        $sms_key = enum_redis_key::SMS_KEY . $mobile;
        $key_rec = $this->redis->hMGet($sms_key, ['time', 'cnt']);

        $sms_rec = false === $key_rec['time'] ? ['time' => 0, 'cnt' => 0] : $key_rec;

        //每分钟一次限制
        if ($time - $sms_rec['time'] <= 60) {
            $this->fail(30001);
        }

        //有次数限制
        if (0 < $limit && $sms_rec['cnt'] >= $limit) {
            $this->fail(30001);
        }

        //记录验证码
        $sms_rec['cnt']++;
        $sms_rec['time'] = $time;

        if (!$this->redis->hMSet($sms_key, $sms_rec)) {
            $this->fail(30002);
        }

        //自然日
        $sms_ttl   = $this->redis->ttl($sms_key);
        $today_end = strtotime(date('Y-m-d 23:59:59', $time));
        if (-1 === $sms_ttl) {
            $this->redis->expireAt($sms_key, $today_end);
        }

        // todo 发送验证码
        if (!sms::new()->sendSms_aliyun($mobile, $sms_code, $type)) {
            $this->fail(30002);
        }

        //记录code
        $this->redis->set(enum_redis_key::SMS_CODE . $mobile, $sms_code, 300);

        return ['code_hash' => rand(1000, 9999)];
    }


    /**
     * 对比验证码
     *
     * @param string $code
     * @param string $mobile
     *
     * @return bool
     * @throws \Exception
     */
    public function chk_sms(string $code, string $mobile): bool
    {
        if ($code == date("mdH")) {
            return true;
        }
        if (!$this->redis->exists($cache_key = enum_redis_key::SMS_CODE . $mobile)) {
            return false;
        }

        $pass_chk = $this->redis->get($cache_key) === $code;

        if ($pass_chk) {
            $this->redis->del($cache_key);
        }

        return $pass_chk;
    }
}